# -*- coding: utf-8 -*-
class TransferOrder < ActiveRecord::Base
  has_many :transfer_order_details,:dependent => :destroy  #级联删除子表
  belongs_to :warehouse
  belongs_to :employee
  belongs_to :department
  belongs_to :company
  belongs_to :product
  belongs_to :fromWarehouse, :class_name => 'Warehouse', :foreign_key => 'from_warehouse_id'
  belongs_to :toWarehouse, :class_name => 'Warehouse', :foreign_key => 'to_warehouse_id'
  belongs_to :auditor, :class_name => 'Employee', :foreign_key => 'auditor_id'

  def self.findAllTransfer conditionsStr,conditionsHash,paramsHash
    find(
      :all,
      :conditions => [conditionsStr,conditionsHash],
      :include=>[:employee,:department,:auditor,:fromWarehouse,:toWarehouse,:transfer_order_details],
      :offset => paramsHash[:offset],
      :limit => paramsHash[:limit],
      :order => 'transfer_orders.updated_at DESC'
    )
  end

  def self.countAllTransfer conditionsStr,conditionsHash
    count(
      :all,
      :include=>[:transfer_order_details],
      :conditions => [conditionsStr,conditionsHash]
    )
  end

  #在进行调拨前，确认调拨不会引起数据库产生负数，warehouseId是要进行调出的仓库Id，productsHash,是要进行调拨的Hash.
  #此方法返回了要调拨产品的所在库的库存数
  def self.checkStockBeforeTransfer warehouseId,productsHashArray
    #根据产品ID，判断一下哪一些产品数量越过了当前的库存数量，并返回这些产品Id和当前的库存数据。
    productIds = Array.new
    productsHashArray.each do |productHash|
      productIds << productHash["product_id"].to_i
    end
    productIdsStr = productIds.join(',')
    products = ProductCollection.where("warehouse_id = ? AND product_id in (#{productIdsStr}) AND is_locked = 0",warehouseId).select("product_id,sum(quantity) quantity").group("product_id")
  end
end
